<?php 

namespace App\Console\Appso;

use Illuminate\Support\Facades\Storage;

class AppSo 
{

	private $limit=50;
	private $offset=0;

	private $client;

	private $tag_id;
	public function __construct()
	{
		$this->client = new \GuzzleHttp\Client(['base_uri' => 'https://minapp.com/api/v3/trochili/miniapp/']);
	}

	private function createurl()
	{
		$url="?tag=$this->tag_id&offset=$this->offset&limit=$this->limit";
		return $url;
	}

	private function createfilename()
	{
		return $this->tag_id.'/'.$this->offset.'_'.$this->limit.'.json';
	}


	private function filename($offset,$limit)
	{
		return $this->tag_id.'_'.offset.'_'.limit.'.json';
	}

	public function handle($tag_id)
	{
		$this->tag_id=$tag_id;
		$url=$this->createurl();
		// dd($url);
		$response = $this->client->get($url);
		echo $response->getStatusCode();
		if($response->getStatusCode()==200)
		{
			$body=$response->getBody();
			// dd($body->getContents());
			Storage::disk('local')->put($this->createfilename(), $body->getContents());

			$json=json_decode($body);

			$next=$json->meta->next;
			$meta=$json->meta;
			if($next&&$next!=null)
			{
				$offset=intval($meta->offset);
				$offset+=50;
				$this->offset=$offset;
				$this->handle($tag_id);
			}
		}
	}

	private function nextfetch($url)
	{

		$response = $this->client->get($url);
		if($response->getStatusCode()==200)
		{
			$body=$response->getBody();
			// dd($body->getContents());
			Storage::disk('local')->put($this->createfilename(), $body->getContents());
			$json=json_decode($body);
			$next=$json['meta']['next'];

		}
	}



}


